package com.mdd.common.wechat.handler;

import com.github.binarywang.wxpay.bean.request.WxPayApplyTradeBillV3Request;
import com.github.binarywang.wxpay.bean.result.WxPayApplyBillV3Result;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.mdd.common.enums.ClientEnum;
import com.mdd.common.plugin.wechat.WxPayDriver;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 功能描述: 微信支付账单下载
 *
 * @author lrc
 * @date 2025/2/25 17:50
 */
@Service

public class WechatBillDownHandler {


    public void billDown() {
        WxPayService wxPayService = WxPayDriver.handler(ClientEnum.MNP.getCode());
        WxPayApplyTradeBillV3Request request = new WxPayApplyTradeBillV3Request();
        request.setBillDate("2025-02-25");
        request.setBillType("ALL");
        // 定义输入流和输出流
        FileOutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            WxPayApplyBillV3Result billV3Result = wxPayService.applyTradeBill(request);
            inputStream = wxPayService.downloadV3(billV3Result.getDownloadUrl());
            // 目标文件路径
            String outputFilePath = "微信对账单.xls";


            // 创建输出流
            outputStream = new FileOutputStream(outputFilePath);
            // 定义缓冲区
            byte[] buffer = new byte[1024];
            int length;
            // 读取数据并写入目标文件
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            System.out.println("文件导出成功!");


        } catch (WxPayException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
